const { verifyToken } = require('../utils/token')

/**
 * 解析cookie
 * @param str
 * @param key
 * @returns {*}
 */
const getCookie = (str, key) => {
  let arr = str.replace(/[ ]/g, '').split(';')
  const obj = {}
  for (const item of arr) {
    const [key, value] = item.split('=')
    obj[key] = value || true
  }
  return obj[key]
}

const auth = (req, res, next) => {
  const sessionId = getCookie(req.get('cookie'), 'sessionId')
  const verifyResult = verifyToken(sessionId)
  if (verifyResult) {
    res.locals.currentUser = verifyResult;
    next()
  } else {
    res.render('notLogin', {
      data: JSON.stringify("请登录")
    })
  }
}

exports.auth = auth
